import * as moment from 'moment';
import visitMonthPlanModel from '../model/visitMonthPlanModel';
import consumerRecoderModel from '../model/consumerRecoderModel';
import storeInfoModel from '../model/storeInfoModel';
import dTalkApi from '../core/dTalkApi';
import userCheckInModel from '../model/userCheckInModel';
import storeRecoderModel from '../model/storeRecoderModel';
import emplModel from '../model/empl2Model';

class FormDataService{
    constructor(){}

    
    async getDate(startDate1:any,endDate1:any){
        let startDate: any = '';
        let endDate: any = '';
        if (startDate1 == '' && endDate1 == '') {
            startDate = moment().format('YYYY-MM') + '-01';
            endDate = moment().format('YYYY-MM-DD');
        } else {
            startDate = moment(startDate1).format('YYYY-MM-DD');
            endDate = moment(endDate1).format('YYYY-MM-DD');
        }
        return {startDate:startDate,endDate:endDate}
    }
      
    async getDate2(date3:number,date4:number,startDate:any){
        let dateList: any[] = [];
        // let yearMonth=moment(startDate).format('YYYY-MM')
        let yearMonth=moment(startDate).format('YYYY-MM')
        //获取日期
        for (let index = date3; index <= date4; index++) {
            let new_date: any = '';
            if (date4 < 10) {
                new_date = yearMonth + '-0' + index;
            } else if (date3 < 10 && date4 >= 10) {
                if (index < 10) {
                    new_date =yearMonth + '-0' + index;
                } else {
                    new_date = yearMonth + '-' + index;
                }
            } else if (date3 >= 10) {
                new_date =yearMonth + '-' + index;
            }
            dateList.push(new_date);
        }
        return dateList;
    }

    //权限
    async getAuthrity(leaderId:any,access_token:string){
        let leaderDepts:any[] = [];//领导主观的部门id列表
        let groupName: any[] = [];//角色名称列表
        let leaderInfo = await dTalkApi.getUserDetail(leaderId,access_token);
       //console.log(leaderInfo,'<------------leaderInfo')
        if(leaderInfo){
            //判断是否是主管
            let isLeaderInDepts: string = leaderInfo.isLeaderInDepts || ''
            isLeaderInDepts = isLeaderInDepts.substr(1, isLeaderInDepts.length - 2)
            let arrayLeaderDepts = isLeaderInDepts.split(',')
            arrayLeaderDepts.map(item => {
                if (item.endsWith(":true")) {
                    leaderDepts.push(item.substr(0, item.length - ":true".length))
                }
            }) 
           
            if (!leaderInfo.roles) {
                console.log("---------------未分配角色-------------------------", leaderInfo);
            }else{
                let roles = leaderInfo.roles;  
                roles.map(it => {
                    groupName.push(it.groupName);
                }) 
            }
        }
        return {groupName:groupName,leaderDepts:leaderDepts};
    }

    //数组去重
    async newArray(cache:any){
        let json4: any = {};
        let newArray:any[]=[]
        if(cache.length>0){
            for (let i = 0; i < cache.length; i++) {
                if (!json4[cache[i]]) {
                    newArray.push(cache[i]);
                    json4[cache[i]] = 1;
                }
            }
        }
        return newArray;
    }

    //获取子部门
    async getsonDept(leaderDepts:any[],fetch_child:boolean,access_token:string){
        let list:any[]=[]//所有子部门id列表
        let listNames:any[]=[]//所有的子部门名称
        let userIdData: any[] = []//领导名下所有员工id列表
       /*  let arr:any=[]
        let data5=await emplModel.find({})
        if(data5.length>0){
            for (let index5 = 0; index5 < data5.length; index5++) {
                let element = data5[index5];
                arr.push(element.userId)
            }
        } */
        let dept2:any[]=[]
        if(leaderDepts.length>0){
            for (let index = 0; index < leaderDepts.length; index++) {
                let dept = leaderDepts[index];
                let sonData = await dTalkApi.getSondepIdList(dept, fetch_child,access_token)
                let son_list = sonData.department;
                son_list.push(parseInt(dept));//
                for (let key in son_list) {
                    if (son_list.hasOwnProperty(key)) {
                        let element = son_list[key];
                        list.push(element)
                    }
                }
                let deptData=sonData.dept //{[{id:deptId,name:deptName}]
                for (let key1 in deptData) {
                    if (deptData.hasOwnProperty(key1)) {
                        let element1 = deptData[key1];
                        dept2.push(element1)
                    }
                }
                for (let key3 in sonData.deptNames) {
                    if (sonData.deptNames.hasOwnProperty(key3)) {
                        let element3 = sonData.deptNames[key3];
                        listNames.push(element3)
                    }
                }
                let empList=await visitMonthPlanModel.distinct("userId",{"$and":[{userId:{$ne:''}},{userId:{$ne:null}},{deptId:{$in:son_list}}]})
                //let empList=await visitMonthPlanModel.distinct("userId",{"$and":[{userId:{$ne:''}},{userId:{$ne:null}},{deptId:{$in:son_list}},{userId:{$in:arr}}]})
                for (let key2 in empList) {
                    if (empList.hasOwnProperty(key2)) {
                        let element2 = empList[key2];
                        userIdData.push(element2)
                    }
                }
                // console.log(son_list,'son_listson_listson_listson_list',userIdData)
            }
        }
        return {list:list,userIdData:userIdData,dept:dept2,listNames:listNames};
    }

    //字符春获取图片链接地址
    async getPicURLFromString(m:string){
        let a_pic=m;
        let a_num=a_pic.indexOf(',')
        let s:any=''
        if(a_num==(-1)){
          s=a_pic.substr(2,a_pic.length-4);
        }else{
            let a_pic_two=a_pic.substr(1,a_pic.length-2)
            let arry=a_pic_two.split(',')
            if(arry.length>0){
                for (let index = 0; index < arry.length; index++) {
                    let t = arry[index];
                    let fin=t.substr(1,t.length-2)
                    if(index==0){
                        s+=fin
                    }else{
                        s+=','+fin
                    }
                }
            }
        }
        return s;
    }

    async getPicURLFromArray(cache:any[]){
        let s_m:any=''
        if(cache.length){
            for (let index = 0; index < cache.length; index++) {
                let element = cache[index];
                if(index==0){
                    s_m+=element
                }else{
                    s_m+=','+element
                }
            }
        }
        return s_m;
    }
    
    //统计一个员工一段时间的签到率
    async getCheckInRate_one_employeeDate1ToDate2(userId: string, date1: string, date2: string) {
        let checkIn_oneemployee_count = await userCheckInModel.distinct("date_",{ "$and": [{ date_: { "$gte": date1 } }, { date_: { "$lte": date2 } }], userId: userId, isCheckInNineAm: true });
        let plan_day_count = await visitMonthPlanModel.distinct("planDate", { "$and": [{ planDate: { "$gte": date1 } }, { planDate: { "$lte": date2 } }], userId: userId ,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }]});
        //签到率
        let checkInRate_ = 0;
        if (plan_day_count.length>0) {
            checkInRate_ = (checkIn_oneemployee_count.length / plan_day_count.length);
          
        } else {
            checkInRate_ = 0;
        }
        return checkInRate_;
    }

    //统计一个员工一段时间的客户拜访达成率
    async getConsumerRate_one_employeeDate1ToDate2(userid: string, date1_: string, date2_: string) {
        //实际已经拜访的客户数量
        let count_visited_consumer = await consumerRecoderModel.count({ "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userid: userid, comment: 2});
        let count_visited_store=await storeRecoderModel.count({"$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userid: userid})
        //计划拜访的客户数量
        let count_plan_consumer = await visitMonthPlanModel.count({ "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userId: userid,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
        let consumerRate_ = 0;
        if (count_plan_consumer == 0) {
            consumerRate_ = 0;
        } else {
            consumerRate_ = (count_visited_consumer+count_visited_store) / count_plan_consumer;
        }
        return consumerRate_;
    }

    //统计一个员工一段时间的新客户的拜访达成率
    async getRate_NewConsumer_one_employeeDate1ToDate2(userid: string, date1_: string, date2_: string) {
        //实际已经拜访的新客户数量
        let count_visited_new_consumer = await consumerRecoderModel.count({ "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userid: userid, planType: '新拓展客户', comment: 2 });
        //计划拜访的新客户数量
        let count_plan_new_consumer = await visitMonthPlanModel.count({ "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userId: userid, plantype: '新拓展客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
        //新客户拜访达成率
        let new_consumerRate_ = 0;
        if (count_plan_new_consumer == 0) {
            new_consumerRate_ = 0;
        } else {
            new_consumerRate_ = (count_visited_new_consumer / count_plan_new_consumer);
        }
        return new_consumerRate_;
    }

    //统计一个员工一段时间的已拜访门店的拜访达标率
    async getReachStoreRate_one_employeeDate1ToDate2(userid: string, date1_: string, date2_: string) {
        //查询一个员工一个时间段已拜访门店并且门店达标的数量    
        let number_ = await storeRecoderModel.count({ userid: userid, "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], planType: '门店', isListStandard: true });
        //一个员工一个时间段已拜访门店的数量
        let visitedStoreCount = await storeRecoderModel.count({ userid: userid, "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], planType: '门店' });
        //门店达标率 
        let reachStoreRate = 0;
        if (visitedStoreCount == 0) {
            reachStoreRate = 0;
        } else {
            reachStoreRate = (number_ / visitedStoreCount);
        }
        return reachStoreRate;
    }

    //统计一个员工一段时间的门店拜访进度
    async getShop_schedule_one_employeeDate1ToDate2(userid: string, date1_: string, date2_: string) {
        //员工名下的所有的门店
        let conList = await consumerRecoderModel.distinct("consumerCode", { userid: userid, comment: 1 });
        let count_totalStore_oneEmployee = await storeInfoModel.count({ consumerCode: { $in: conList } });
        //已拜访的门店数量
        let count_store = await storeRecoderModel.count({ userid: userid, "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }] });
        //门店拜访进度
        let shop_schedule = 0;
        if (count_totalStore_oneEmployee == 0) {
            shop_schedule = 0;
        } else {
            shop_schedule = (count_store / count_totalStore_oneEmployee);
        }
        return shop_schedule;
    }

    //一个员工一个时间段的出差频率
    async getgetTravelFrequency_oneemployeeDate1ToDate2(userid: string, date1_: string, date2_: string) {
        //这一段时间上班的天数  
        let plan_data = await visitMonthPlanModel.distinct("planDate", { "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userId: userid, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] })
        //一段时间内一个员工出差的次数
        let store_date= await storeRecoderModel.distinct("planDate",{ userid: userid, isChuchai: true ,"$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }]});
        let con_date = await consumerRecoderModel.distinct("planDate",{ userid: userid, isChuchai: true, comment: 2,"$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }] })
        let newArray=con_date.concat(store_date)
        let dateList=await formDataService.newArray(newArray);
        //一个员工这一时间段的出差频率
        let travelFrequency_: any = 0;
        if (plan_data.length == 0) {
            travelFrequency_ = 0;
        } else {
            travelFrequency_ = dateList.length / plan_data.length;
        }
        return travelFrequency_;
    }
 
    //统计一个员工名下面的门店数量和客户数量
    async countTotalStoreOrConsumerByEmployeeId(userid: string) {
        let con_data=await consumerRecoderModel.distinct("consumerCode",{userid:userid,comment:1})
        let store_count=await storeInfoModel.count({consumerCode:{$in:con_data}})
        return {con_count:con_data.length,store_count:store_count}
    }
    //统计一个员工一段时间的客户拜访的数量
    async getCountConsumer_one_employeeDate1ToDate2(userid: string, date1_: string, date2_: string) {
        //实际已经拜访的客户数量
        let count_visited_consumer = await consumerRecoderModel.count({ "$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userid: userid, comment: 2});
        let count_visited_store=await storeRecoderModel.count({"$and": [{ planDate: { "$gte": date1_ } }, { planDate: { "$lte": date2_ } }], userid: userid})
        
        let count=count_visited_consumer+count_visited_store;
        return count;
    }
    
        
  
}
let formDataService = new FormDataService();
export default formDataService;